﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

namespace WellDone
{
    public sealed partial class TablePicker : Page
    {
        public event EventHandler CloseRequested;
        public bool bUpdated = false;
        public string tableNo = "-1";
        public TablePicker()
        {
            this.InitializeComponent();
        }
       
        public async Task<Boolean> init()
        {
            await loadTableLayouts();
            var pane = InputPane.GetForCurrentView();
            pane.Showing += pane_Showing;
            pane.Hiding += pane_Hiding;
            return true;
        }

        private async Task<Boolean> loadTableLayouts()
        {
            LayoutContainer.Children.Clear();
            // Retrieve table layout records
            Globals.TableLayoutRecords = await Globals.client.GetTableLayoutObjectsAsync(Globals.token, "1=1");
            ddlLayout.Items.Clear();
            // Retrieve list of layout records
            foreach (ServiceReferenceOpenRPOS.TableLayout tl in Globals.TableLayoutRecords)
            {
                ddlLayout.Items.Add(new ComboBoxItem() { Tag = tl.col_ID, Content = tl.col_Name.Trim() });
            }
            ddlLayout.SelectedIndex = 0;
            return true;
        }

        private async void ddlLayout_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string tableLayout = "-1";
            if (((ComboBox)sender).SelectedItem != null)
            {
                tableLayout = ((ComboBox)sender).SelectedValue.ToString();
                Globals.TableLayoutRecords = await Globals.client.GetTableLayoutObjectsAsync(Globals.token, "ID=" + tableLayout);
                LayoutContainer.Children.Clear();
                if (Globals.TableLayoutRecords.Count > 0)
                {
                    lblHeader.Text  = Globals.TableLayoutRecords[0].col_Name + " (Width : " + Globals.TableLayoutRecords[0].col_Length + ", Height : " + Globals.TableLayoutRecords[0].col_Width + ")";
                    LayoutContainer.Width = Globals.TableLayoutRecords[0].col_Length;
                    LayoutContainer.Height = Globals.TableLayoutRecords[0].col_Width;

                    LayoutContainer.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
                    LayoutContainer.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                    await loadTables(tableLayout);
                }
            }
        }

        private async Task<Boolean> loadTables(string tableLayout)
        {
            // Retrieve table specification records
            Globals.TableSpecificationRecords = await Globals.client.GetTableSpecificationObjectsAsync(Globals.token, "TableLayoutID=" + tableLayout);
            // Retrieve list of table specification
            foreach (ServiceReferenceOpenRPOS.TableSpecification ts in Globals.TableSpecificationRecords)
            {
                CreateCanvas(ts);
            }
            return true;
        }

        private void CreateCanvas(ServiceReferenceOpenRPOS.TableSpecification oTableSpecification)
        {
            try
            {
                string canvasName = Convert.ToString(oTableSpecification.col_TableNumber);
                string canvasID = Convert.ToString(oTableSpecification.col_ID);
                double width = oTableSpecification.col_Length;
                double height = oTableSpecification.col_Width;
                double top = oTableSpecification.col_CenterY;
                double left = oTableSpecification.col_CenterX;
                bool tableType = (oTableSpecification.col_Rectangle ? true : false);

                FrameworkElement controlCanvas = null;
                TextBlock tableno = new TextBlock();    

                if (tableType) controlCanvas = new Rectangle();
                else controlCanvas = new Ellipse();
                if (controlCanvas != null)
                {
                    controlCanvas.Name = canvasID;
                    controlCanvas.Tag = canvasName;
                    tableno.Text = canvasName;

                    controlCanvas.Width = width;
                    controlCanvas.Height = height;

                    controlCanvas.SetValue(Canvas.LeftProperty, left);
                    controlCanvas.SetValue(Canvas.TopProperty, top);

                    tableno.SetValue(Canvas.LeftProperty, left + (width / 2) -2-  (canvasName.Count()/2)*5);
                    tableno.SetValue(Canvas.TopProperty, top + (height / 2) - 6);

                    LinearGradientBrush fiveColorRGB = new LinearGradientBrush();
                    GradientStop blueGS = new GradientStop();
                    Color tableColor = Colors.Blue;

                    if (oTableSpecification.col_Occupied == true) tableColor = Colors.Green;
                    //else //As discussed, we have allowed to select occupied table for multiple order(s).
                    //{
                        controlCanvas.Tapped += controlCanvas_Tapped;
                        tableno.Tapped += tableno_Tapped;
                    //}
                    blueGS.Color = tableColor;

                    fiveColorRGB.GradientStops.Add(blueGS);
                    ((Shape)controlCanvas).Fill = fiveColorRGB;

                    LinearGradientBrush textForeground = new LinearGradientBrush();
                    GradientStop WhiteGS = new GradientStop();

                    WhiteGS.Color = Colors.White;

                    textForeground.GradientStops.Add(WhiteGS);
                    tableno.Foreground = textForeground;

                    tableno.FontWeight = Windows.UI.Text.FontWeights.Bold;
                    tableno.FontSize = 12;

                    var myElement = (LayoutContainer.Children.SingleOrDefault<UIElement>(label => label.GetValue(FrameworkElement.NameProperty).ToString() == Convert.ToString(controlCanvas.Name)));

                    if (myElement == null)
                    {
                        LayoutContainer.Children.Add(controlCanvas);
                        LayoutContainer.Children.Add(tableno);
                    }
                }
            }
            catch (Exception ex)
            {
                //log exception 
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

        }

        private void tableno_Tapped(object sender, TappedRoutedEventArgs e)
        {
            bUpdated = true;
            tableNo = Convert.ToString(((TextBlock)(sender)).Text);
            // Close the dialog
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }

        private void controlCanvas_Tapped(object sender, TappedRoutedEventArgs e)
        {
            bUpdated = true;
            tableNo =  Convert.ToString(((Windows.UI.Xaml.FrameworkElement)(sender)).Tag);
            // Close the dialog
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }

        private void pane_Showing(InputPane sender, InputPaneVisibilityEventArgs e)
        {
            // Shift the dialog up...
            this.RootPanel.Margin = new Thickness(0, -1 * e.OccludedRect.Y, 0, 0);
        }
        
        private void pane_Hiding(InputPane sender, InputPaneVisibilityEventArgs e)
        {
            // Restore...
            this.RootPanel.Margin = new Thickness(0, 0, 0, 0);
        }
        
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            bUpdated = false;
            // Close the dialog
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }
    }
}
